﻿package demo.utils
{    
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.utils.getTimer;
	import flash.text.TextFormat;
	
	public class FrameRateCounter extends Sprite
	{
		
		private var _framerateLabel:TextField;
		private var _lastTimeStamp:Number;
		private var _frameCount:Number;
		
		public function FrameRateCounter()
		{
			super();
			addEventListener(Event.ADDED_TO_STAGE, createChildren, false, 0, true);
		}
		
		private function createChildren(evt:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, createChildren);
			_framerateLabel = new TextField();
			_framerateLabel.width = 400;
			_framerateLabel.defaultTextFormat = new TextFormat(null, 24);
			_framerateLabel.selectable = false;
			addChild(_framerateLabel);
			startMonitoringFrameRate();
		}
		
		private function startMonitoringFrameRate():void
		{
			_lastTimeStamp = getTimer();
			_frameCount = 0;
			addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0, true);
		}
		
		private function onEnterFrame(evt:Event):void
		{
			_frameCount++;
			var currentTime:Number = getTimer();
			var elapsedTime:Number = currentTime - _lastTimeStamp;
			if(elapsedTime > 1000){
				updateFrameCountLabel(elapsedTime);
				_lastTimeStamp = currentTime;
				_frameCount = 0;
			}
		}
		
		private function updateFrameCountLabel(elapsedTime:Number):void
		{
			var framesPerMillisecond:Number = _frameCount/elapsedTime;
			var framesPerSecond:Number = Math.floor(framesPerMillisecond*1000);
			_framerateLabel.text = "Frames: " + framesPerSecond;
		}
	}
}